package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.BuildConfig;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.BuyCarFragment;
import com.gongpingjialoan.activity.car.CollectActivity;
import com.gongpingjialoan.activity.car.RecomendDiscountFragment;
import com.gongpingjialoan.activity.car.SellCarHistoryActivity;
import com.gongpingjialoan.activity.category.AssessmentFragment;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.search.TopSearchActivity;
import com.gongpingjialoan.activity.sell.NewSellCarFragment;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.Domain;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.UpdateBean;
import com.gongpingjialoan.data.CarListFilterData;
import com.gongpingjialoan.data.CityData;
import com.gongpingjialoan.data.NewCarActivityData;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.NetReceiver;
import com.gongpingjialoan.utility.ApkUpdateUtils;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.StepRecord;
import com.gongpingjialoan.utility.Utils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.utils.v4.FragmentPagerItemAdapter;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 主界面 wang
 *
 * @author Administrator
 */
public class MainActivity extends BaseActivity

{
    public static final String USERHOME = "USERHOME";

    private static final String CITY_CHANGE_ACTION = "com.gongpingjia.city";

    private static final String NET_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";

    public static final int MIN_CLICK_DELAY_TIME = 100;

    public static final int GETMORE_DOAMIN = 898;

    public static final int ALL_BRAND = 888;

    private long lastClick;

    private CityData mCityData;

    public String fromType;

    public boolean mNeedProvince;

    private boolean isExit = false;

    private Handler mHandler;

    private TextView titleT, titleF;

    private TextView title_rightI;

    private ImageView settingI;

    private LinearLayout titleView;

    private LinearLayout tabV;

    // 买车页面,导航栏的切换
    private RadioGroup titleRadio;

//    // 好车推荐帮你找车,导航栏的切换
//    private RadioGroup chooseRadioGroup;

    // 标题栏左边的放大镜按钮
    private ImageView title_leftI;

    public static MainActivity main;

    private NetReceiver netReceiver;

    private int current = -1;

    public RadioButton brandRadioButton;

    public RadioButton buycarRadioButton;

//    public RadioButton recomendRadioButton;
//
//    public RadioButton chooseRadioButton;

    public boolean isShowVip = true;

    private ImageView myCarImageView;

    //评估页面
    public AssessmentFragment assessmentFragment;

    //买车页面
    public BuyCarFragment buyCarFragment;


    //卖车页面
    public NewSellCarFragment sellCarFragment;

    //用户页面
//    public UserHomeFragment userHomeFragment;
    public UserHomeFragment mUserHomeFragment;

    //推荐好车帮你选车页面
    //public MainCarFragment mMainCarFragment;
    public RecomendDiscountFragment mRecomendDiscountFragment;

    private Fragment mContent;

    public String currentCity = "";

    private CityChangeReceiver mChangeReceiver;

    private Toast mToast;

    private TextView recommd_car_tv;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };
    private boolean hasNewCar = false;
    private ImageView share_img;


//    private void initWindow() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//          //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        }
//    }

    //
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_new);
        setSwipeEnagle();
        EventBus.getDefault().register(this);
        main = this;
        mHandler = new Handler();
        MiPushClient.setAlias(this, GPJApplication.getInstance().getDeviceCode(), null);
        titleView = (LinearLayout) findViewById(R.id.title_bar);
        titleT = (TextView) findViewById(R.id.top_title);
        settingI = (ImageView) findViewById(R.id.setting);
        settingI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });
        title_rightI = (TextView) findViewById(R.id.kefu_id);
        title_rightI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000253500"));
                startActivity(intent);
            }
        });


        titleRadio = (RadioGroup) findViewById(R.id.title_tab);

        titleRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkId) {
                if (checkId == R.id.radio_new) {
                    buyCarFragment.changCarListFragment();
                    title_leftI.setVisibility(View.VISIBLE);
                    titleF.setVisibility(View.VISIBLE);
                    share_img.setVisibility(View.GONE);

                } else if (checkId == R.id.radio_experts) {
                    if (hasNewCar) {
                        buyCarFragment.changNewCarFragment();
                        share_img.setVisibility(View.VISIBLE);
                    } else {
                        buyCarFragment.changRankFragment();
                        share_img.setVisibility(View.GONE);
                    }
                    title_leftI.setVisibility(View.GONE);
                    titleF.setVisibility(View.GONE);
                }
            }
        });

        title_leftI = (ImageView) findViewById(R.id.title_left);
        titleF = (TextView) findViewById(R.id.top_filter);
        brandRadioButton = (RadioButton) findViewById(R.id.radio_experts);
        buycarRadioButton = (RadioButton) findViewById(R.id.radio_new);


        titleF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if ("0".equals(arg0.getTag().toString())) {
                    buyCarFragment.showFilterView();
                } else {
                    startActivity(new Intent(main, CollectActivity.class));
                }

            }
        });
        title_leftI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "buy_dealer_search", System.currentTimeMillis(), 1.0f));
                Intent intent = new Intent(MainActivity.this,
                        TopSearchActivity.class);
                startActivity(intent);
            }
        });

        tabV = (LinearLayout) findViewById(R.id.tab);
        tabV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        initTab();
        fromType = getIntent().getStringExtra("type");
        //推送用
        String source = getIntent().getStringExtra("source");
        String job_id = getIntent().getStringExtra("job_id");
        //获取城市数据
        mCityData = ((GPJApplication) getApplication()).getCityData();
        mCityData.mCurrentCity = Utils.getCityName(this);
        currentCity = mCityData.mCurrentCity;

        assessmentFragment = new AssessmentFragment();
        buyCarFragment = new BuyCarFragment();
        sellCarFragment = new NewSellCarFragment();
//        userHomeFragment = new UserHomeFagment();
        mUserHomeFragment = new UserHomeFragment();
        mRecomendDiscountFragment = new RecomendDiscountFragment();
        //  mMainCarFragment = new MainCarFragment();
        if (MyPushIntentService.MARKET.equals(fromType) || MyPushIntentService.BILLBOARD.equals(fromType) || MyPushIntentService.BILLBOARDTYPE.equals(fromType)) {
            setTab(3, true);
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + getIntent().getStringExtra("typevalue") + ",source:" + source + ",job_id:" + job_id + "}");
        } else if (MyPushIntentService.CHOOSECAR.equals(fromType) || MyPushIntentService.RECOMMEND.equals(fromType) || MyPushIntentService.PROMINTIONLIST.equals(fromType)) {
            setTabfour(4, true);
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + "" + ",source:" + source + ",job_id:" + job_id + "}");
        } else if (MyPushIntentService.SELLCAR.equals(fromType)) {
            setTab(1, true);
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + "" + ",source:" + source + ",job_id:" + job_id + "}");
        } else {
            setTab(0, true);
        }
        share_img = (ImageView) findViewById(R.id.share_img);
        share_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                share();
            }
        });
        registerLoadDataBoardCast();
        getNewVersion();
        //    upDate();
        getNewCarActivity("");
    }


    //应用运行时  推送过来的页面
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        fromType = "";
        String type = "";
        Bundle mBundle = intent.getExtras();
        //推送用
        if (mBundle != null) {
            fromType = mBundle.getString("type", "");
            type = mBundle.getString("typevalue", "");
            if (!USERHOME.equals(fromType) && !"sellCar".equals(fromType) && !"pay".equals(fromType) && !"findcarHistory".equals(fromType) && !"sell_car".equals(fromType) && !"eval_car".equals(fromType) && !"sell_private_car".equals(fromType)) {
                String source = mBundle.getString("source", "");
                String job_id = mBundle.getString("job_id", "");
                StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + type + ",source:" + source + ",job_id:" + job_id + "}");
            }
        }
        if (MyPushIntentService.BILLBOARD.equals(fromType) || MyPushIntentService.BILLBOARDTYPE.equals(fromType) || USERHOME.equals(fromType)) {
            gototop(type);
        } else if (MyPushIntentService.PROMINTIONLIST.equals(fromType)) {
            gorecomendcar();
        } else if (MyPushIntentService.MARKET.equals(fromType)) {
            gotocheshi();
        } else if (MyPushIntentService.RECOMMEND.equals(fromType)) {
            gorecomendcar();
        } else if (MyPushIntentService.CHOOSECAR.equals(fromType) || "findcarHistory".equals(fromType)) {
            //gochoosecar();
            gotocheshi();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    buyCarFragment.showFilterView();
                }
            }, 500);
        } else if ("sellCar".equals(fromType)) {
            //历史页面
            startActivity(new Intent(this, SellCarHistoryActivity.class));
        } else if ("sell_car".equals(fromType)) {
            //从bannar跳转
            setTab(1, true);
        } else if (MyPushIntentService.SELLCAR.equals(fromType)) {
            //推送跳转
            if (sellCarFragment.isAdded()) {
                sellCarFragment.getPushData();
            }
            setTab(1, true);
        } else if ("eval_car".equals(fromType)) {
            //从bannar跳转
            setTab(0, true);
        } else if ("sell_private_car".equals(fromType)) {
            Intent i = new Intent(this, SellCarHistoryActivity.class);
            i.putExtra("private", true);
            startActivity(i);
        } else if ("pay".equals(fromType)) {
            Intent i = new Intent(this, OrderActivity.class);
            startActivity(i);
        }else if("buycar".equals(fromType)){
            setTab(3, true);
        }
    }


    //    public void gochoosecar() {
//        if (mMainCarFragment.mChooseCarFragment != null && mMainCarFragment.mChooseCarFragment.isAdded()) {
//            setTabfour(4, true);
//            chooseRadioButton.setChecked(true);
//            mMainCarFragment.mChooseCarFragment.refreshData();
//        } else {
//            setTabfour(4, true);
//        }
//    }
//
//
    private void gorecomendcar() {
        setTabfour(4, true);
    }


    //去榜单页面
    public void gototop(String type) {
        if (hasNewCar) {
            startActivity(new Intent(this, RankActivity.class).putExtra("type", type));
        }else{
            if (buyCarFragment.rankFragment != null && buyCarFragment.rankFragment.isAdded()) {
                setTab(3, true);
                brandRadioButton.setChecked(true);
                buyCarFragment.updateRankListData(type);
            } else {
                setTab(3, true);
                if (buyCarFragment.isAdded()) {
                    buyCarFragment.changeFragment();
                }
            }
        }
    }


    public void changeToTopFragment(final String type) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("type", USERHOME);
        intent.putExtra("typevalue", type);
        startActivity(intent);
    }


    //推送去车市页面
    public void gotocheshi() {
        if (buyCarFragment.carListFragment != null && buyCarFragment.carListFragment.isAdded()) {
            setTab(3, true);
            if (!buycarRadioButton.isChecked()) {
                buycarRadioButton.setChecked(true);
            }
            buyCarFragment.updateListData("");
        } else {
            isShowVip = false;
            setTab(3, true);
            if (buyCarFragment.isAdded()) {
                buyCarFragment.changeFragment();
            }
        }
    }

    //如果数据未加载，在再次加载数据
    private void registerLoadDataBoardCast() {
        //监听城市变化
        mChangeReceiver = new CityChangeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CITY_CHANGE_ACTION); // 为BroadcastReceiver指定action，使之用于接收同action的广播
        getApplicationContext().registerReceiver(mChangeReceiver, intentFilter);

        netReceiver = new NetReceiver();
        IntentFilter filter = new IntentFilter();//生成一个IntentFilter对象
        filter.addAction(NET_CHANGE);//为IntentFilter添加一个Action
        getApplicationContext().registerReceiver(netReceiver, filter);//将BroadcastReceiver对象注册到系统当中
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (BuildConfig.LEO_DEBUG) {
            super.onSaveInstanceState(outState);
        }
    }


    //解除广播
    private void unregisterLoadDataBoardCast() {
        if (netReceiver != null) {
            getApplicationContext().unregisterReceiver(netReceiver);
        }
        if (mChangeReceiver != null) {
            getApplicationContext().unregisterReceiver(mChangeReceiver);
        }
    }


    public TextView getFilterTextView() {
        return titleF;
    }


    private void switchContent(Fragment to) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mContent == null) {
            transaction.add(R.id.main_content, to, to.getClass().getName()).commitAllowingStateLoss();
            mContent = to;
        } else {
            if (mContent != to) {
                if (!to.isAdded()) {    // 先判断是否被add过
                    transaction.hide(mContent).add(R.id.main_content, to, to.getClass().getName()).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(mContent).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
                }
                mContent = to;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                mToast = Toast.makeText(this, "再按一次退出程序",
                        Toast.LENGTH_SHORT);
                mToast.show();
                mHandler.postDelayed(runnable, 2000);
            } else {
                mToast.cancel();
                getScrollPagesHeight();
                StepMonitor.getInstance().addMonitorSend(new Monitor("enter", "exit", System.currentTimeMillis(), 1f));
                StepMonitor.getInstance().isClose = true;
                EMClient.getInstance().logout(true, new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        System.exit(0);
                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
//                finish();
//
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void getScrollPagesHeight() {
        if (assessmentFragment.isAdded()) {
            StepMonitor.getInstance().addMonitor(new Monitor("scroll", assessmentFragment.action, System.currentTimeMillis(), assessmentFragment.roll_pages));
        }
        if (buyCarFragment.isAdded() && buyCarFragment.carListFragment != null && buyCarFragment.carListFragment.isAdded()) {
            StepMonitor.getInstance().addMonitor(new Monitor("scroll", buyCarFragment.carListFragment.action, System.currentTimeMillis(), buyCarFragment.carListFragment.roll_pages));
        }

        if (buyCarFragment.isAdded() && buyCarFragment.rankFragment != null && buyCarFragment.rankFragment.isAdded()) {
            FragmentPagerItemAdapter adapter = buyCarFragment.rankFragment.adapter;
            int current = buyCarFragment.rankFragment.currentItem;
            if (adapter != null) {
                BaseScrollFragment baseScrollFragment = (BaseScrollFragment) adapter.getPage(current);
                StepMonitor.getInstance().addMonitor(new Monitor("scroll", baseScrollFragment.action, System.currentTimeMillis(), baseScrollFragment.roll_pages));
            }
        }

        if (sellCarFragment.isAdded()) {
            StepMonitor.getInstance().addMonitor(new Monitor("scroll", sellCarFragment.action, System.currentTimeMillis(), sellCarFragment.roll_pages));
        }
        if (mRecomendDiscountFragment.isAdded()) {
            StepMonitor.getInstance().addMonitor(new Monitor("scroll", mRecomendDiscountFragment.action, System.currentTimeMillis(), mRecomendDiscountFragment.roll_pages));
        }


    }


    private void initTab() {
        for (int i = 0; i < tabV.getChildCount(); i++) {
            if (i == 2) continue;
            final int index = i;
            View childV = tabV.getChildAt(i);
            childV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (System.currentTimeMillis() - lastClick <= MIN_CLICK_DELAY_TIME) {
                        return;
                    }
                    lastClick = System.currentTimeMillis();
                    setTab(index, true);
                }
            });
        }
        recommd_car_tv = (TextView) findViewById(R.id.recommd_car_tv);
        myCarImageView = (ImageView) this.findViewById(R.id.mycar);
        myCarImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (System.currentTimeMillis() - lastClick <= MIN_CLICK_DELAY_TIME || 4 == current) {
                    return;
                }
                lastClick = System.currentTimeMillis();
                setTabfour(4, true);
            }
        });
    }


    public void setTabfour(int index, boolean isNeedSwitch) {
        if (isNeedSwitch) {
            if (index == current)
                return;
            resetTab();
            switchContent(mRecomendDiscountFragment);
        }
        title_leftI.setVisibility(View.GONE);
        titleRadio.setVisibility(View.GONE);
        titleF.setVisibility(View.GONE);
        share_img.setVisibility(View.GONE);
        title_rightI.setVisibility(View.GONE);
        settingI.setVisibility(View.GONE);
        titleView.setVisibility(View.GONE);

        mNeedProvince = false;
        myCarImageView.setImageResource(R.drawable.good_car_select);
        recommd_car_tv.setTextColor(getResources().getColor(R.color.new_color));
        current = index;
    }


    private void resetTab() {
        for (int i = 0; i < tabV.getChildCount(); i++) {
            if (i == 2) continue;
            ViewGroup childV = (ViewGroup) tabV.getChildAt(i);
            ImageView img = (ImageView) childV.getChildAt(0);
            TextView textView = (TextView) childV.getChildAt(1);
            switch (i) {
                case 0:
                    img.setImageResource(R.drawable.eval_icon_normal);
                    textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                    break;

                case 1:
                    img.setImageResource(R.drawable.sellcar_icon_normal);
                    textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                    break;

                case 3:
                    img.setImageResource(R.drawable.buycar_normal);
                    textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                    break;

                case 4:
                    img.setImageResource(R.drawable.my_normal);
                    textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                    break;

                default:
                    break;
            }
        }
    }

    public void setTab(int index, boolean isNeedSwitch) {
        for (int i = 0; i < tabV.getChildCount(); i++) {
            if (i == 2) continue;
            ViewGroup childV = (ViewGroup) tabV.getChildAt(i);
            ImageView img = (ImageView) childV.getChildAt(0);
            TextView textView = (TextView) childV.getChildAt(1);
            if (index == i) {
                myCarImageView.setImageResource(R.drawable.good_car);
                switch (index) {
                    case 0:
                        if (isNeedSwitch) {
                            if (0 == current)
                                return;
                            switchContent(assessmentFragment);
                        }
                        title_rightI.setTag(0);
                        titleView.setVisibility(View.GONE);
                        img.setImageResource(R.drawable.eval_icon_select);
                        textView.setTextColor(getResources().getColor(R.color.new_color));
                        mNeedProvince = false;
                        current = 0;
                        recommd_car_tv.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    case 1:
                        if (isNeedSwitch) {
                            if (1 == current)
                                return;
                            switchContent(sellCarFragment);
                        }

                        title_rightI.setTag(3);
                        title_leftI.setVisibility(View.GONE);
                        //chooseRadioGroup.setVisibility(View.GONE);
                        titleRadio.setVisibility(View.GONE);
                        img.setImageResource(R.drawable.sellcar_icon_select);
                        textView.setTextColor(getResources().getColor(R.color.new_color));
                        titleT.setText("快速卖车");
                        titleView.setVisibility(View.VISIBLE);
                        titleT.setVisibility(View.VISIBLE);
                        // actionBar.setTitle("估值");
                        settingI.setVisibility(View.GONE);
                        title_rightI.setVisibility(View.VISIBLE);
                        titleF.setVisibility(View.GONE);
                        share_img.setVisibility(View.GONE);
                        mNeedProvince = false;
                        current = 1;
                        recommd_car_tv.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    case 3:
                        if (isNeedSwitch) {
                            if (2 == current)
                                return;
                            switchContent(buyCarFragment);
                        }
                        title_leftI.setVisibility(titleRadio.getCheckedRadioButtonId() == R.id.radio_new ? View.VISIBLE
                                : View.GONE);
                        titleF.setVisibility(titleRadio.getCheckedRadioButtonId() == R.id.radio_new ? View.VISIBLE
                                : View.GONE);
                        if(hasNewCar && titleRadio.getCheckedRadioButtonId() == R.id.radio_experts){
                            share_img.setVisibility(View.VISIBLE);
                        }else{
                            share_img.setVisibility(View.GONE);
                        }

                        titleF.setTag("0");
                        titleF.setTextColor(getResources().getColor(R.color.discount_title));
                        titleF.setText("筛选");
                        titleView.setVisibility(View.VISIBLE);
                        titleRadio.setVisibility(View.VISIBLE);
                        titleT.setVisibility(View.GONE);
                        settingI.setVisibility(View.GONE);
                        // chooseRadioGroup.setVisibility(View.GONE);
                        title_rightI.setVisibility(View.GONE);
                        img.setImageResource(R.drawable.buycar_select);
                        textView.setTextColor(getResources().getColor(R.color.new_color));
                        current = 2;
                        recommd_car_tv.setTextColor(getResources().getColor(R.color.text_desc_color));

                        break;

                    case 4:
                        if (isNeedSwitch) {
                            if (3 == current)
                                return;
                            switchContent(mUserHomeFragment);
//                            switchContent(userHomeFragment);
                        }
                        titleView.setVisibility(View.GONE);
                        img.setImageResource(R.drawable.my_select);
                        textView.setTextColor(getResources().getColor(R.color.new_color));
                        titleT.setText("我的");
                        current = 3;
                        recommd_car_tv.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    default:
                        break;
                }
            } else {

                switch (i) {
                    case 0:
                        img.setImageResource(R.drawable.eval_icon_normal);
                        textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    case 1:
                        img.setImageResource(R.drawable.sellcar_icon_normal);
                        textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    case 3:
                        img.setImageResource(R.drawable.buycar_normal);
                        textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    case 4:
                        img.setImageResource(R.drawable.my_normal);
                        textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                        break;

                    default:
                        break;
                }
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ALL_BRAND) {
                Bundle bundle = data.getExtras();
                CarListFilterData.getInstance().clear();
                CarListFilterData.getInstance().setIsCleanData(true);
                CarListFilterData.getInstance().setBrandSlug(bundle.getString("brandSlug", ""));
                CarListFilterData.getInstance().setBrandName(bundle.getString("brandName", ""));
                CarListFilterData.getInstance().setModelSlug(bundle.getString("modelSlug", ""));
                CarListFilterData.getInstance().setModelName(bundle.getString("modelName", ""));
                gotocheshi();
            } else if (requestCode == GETMORE_DOAMIN) {
                Bundle b = data.getExtras();
                ArrayList<Domain> mDomains = b.getParcelableArrayList("Domain");
                getDomainString(mDomains);
            }
        }
    }

    private void getDomainString(ArrayList<Domain> mDomains) {
        int size = mDomains.size();
        StringBuilder sb = new StringBuilder();
        StringBuilder value = new StringBuilder();
        for (int i = 0; i < size; i++) {
            if (mDomains.get(i).isCheck()) {
                if (i == size - 1) {
                    sb.append(mDomains.get(i).getName());
                    value.append(mDomains.get(i).getValue());
                } else {
                    sb.append(mDomains.get(i).getName()).append(",");
                    value.append(mDomains.get(i).getValue()).append(",");
                }
            }
        }
        String show_domain = sb.toString();
        String str_domain = value.toString();
        CarListFilterData.getInstance().clear();
        CarListFilterData.getInstance().setIsCleanData(true);
        CarListFilterData.getInstance().setShow_domain(show_domain);
        CarListFilterData.getInstance().setCar_domain(str_domain);
        gotocheshi();
    }

    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterLoadDataBoardCast();
        mHandler.removeCallbacks(runnable);
        CarListFilterData.getInstance().clear();
        AssessmentData.getInstance().clear();
        main = null;
    }



    class CityChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (CITY_CHANGE_ACTION.equals(arg1.getAction())) {
                String city = Utils.getCityName(getApplicationContext());
                currentCity = city;
                mCityData.mCurrentCity = city;
                if (!(boolean) SharedPreferencesUtil.get(getApplicationContext(), "isChangeCity", false)) {
                    Utils.changeCity(city);
                }
                getNewCarActivity("");
                //刷新城市
                if (assessmentFragment != null && assessmentFragment.isAdded()) {
                    assessmentFragment.changCity(city);
                }
                //刷新抢好车页面   当前城市发生改变时
                if (mRecomendDiscountFragment != null && mRecomendDiscountFragment.isAdded() && !city.equals(currentCity)) {
                    mRecomendDiscountFragment.currentCity = city;
                    mRecomendDiscountFragment.updateDiscountListData();

                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if ("notification".equals(o.toString())) {
//            if (assessmentFragment.isAdded()) {
//                assessmentFragment.setBanerImage();
//            }
//            if (sellCarFragment.isAdded()) {
//                sellCarFragment.initBanner();
//            }
        } else if ("hotCarloaded".equals(o.toString())) {
            if (assessmentFragment.isAdded()) {
                assessmentFragment.mHotParamersView.initBrand();
            }
        }
    }


    private void upDate(final UpdateBean updateBean) {
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setTitle("发现新版本" + updateBean.getData().getVersion());
        ab.setMessage(updateBean.getData().getDescription());
        final boolean isForce = updateBean.getData().isForce_update();
        if (!isForce) {
            ab.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        } else {
            ab.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    System.exit(0);
                }
            });
        }
        ab.setPositiveButton("更新", null);
        final AlertDialog alertDialog = ab.create();
        if (isForce) {
            alertDialog.setCancelable(false);
        }
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!canDownloadState()) {
                    Toast.makeText(main, "请您启用下载服务", Toast.LENGTH_SHORT).show();
                    showDownloadSetting();
                    return;
                }
                ApkUpdateUtils.download(main, updateBean.getData().getDownload_url(), getResources().getString(R.string.app_name), isForce);
                if (!isForce) {
                    alertDialog.dismiss();
                }
            }
        });

    }


    private void getNewVersion() {
        NetDataJson updateNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                UpdateBean updateBean = gson.fromJson(json, UpdateBean.class);
                if ("success".equals(updateBean.getStatus()) && updateBean.getData() != null && !TextUtils.isEmpty(updateBean.getData().getDownload_url())) {
                    upDate(updateBean);
                }
            }
        }, 1);
        updateNetDataJson.setUrl(API.update);
        updateNetDataJson.request("get");
    }

    /**
     * 新车活动
     */
    public void getNewCarActivity(String city) {
        if (!TextUtils.isEmpty(city)) {
            currentCity = city;
        }
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                getSharedPreferences("NEW_CAR_ACTIVITY", MODE_PRIVATE).edit().putString("campaign_id", "").commit();
                hasNewCar = false;
                brandRadioButton.setText("榜单");
                buycarRadioButton.setText("车市");
                share_img.setVisibility(View.GONE);
                if (buyCarFragment != null && buyCarFragment.isAdded()) {
                    if (titleRadio.getCheckedRadioButtonId() == R.id.radio_new) {
                        buyCarFragment.changCarListFragment();
                    } else {
                        buyCarFragment.changRankFragment();
                    }
                    if (buyCarFragment.carListFragment != null && buyCarFragment.carListFragment.isAdded()) {
                        buyCarFragment.carListFragment.updateBanner(hasNewCar);
                    }
                }
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String id = jsonObject.getString("id");
                    getSharedPreferences("NEW_CAR_ACTIVITY", MODE_PRIVATE).edit().putString("campaign_id", id).commit();
                    hasNewCar = true;
                    brandRadioButton.setText("新车");
                    buycarRadioButton.setText("二手车");
                    share_img.setVisibility(titleRadio.getCheckedRadioButtonId() == R.id.radio_new ? View.GONE
                            : View.VISIBLE);
                } catch (JSONException e) {
                    Utils.LogE("getNewCarActivity JSONException e ：" + e.getMessage());
                }

                if (buyCarFragment != null && buyCarFragment.isAdded()) {
                    if (titleRadio.getCheckedRadioButtonId() == R.id.radio_new) {
                        buyCarFragment.changCarListFragment();
                    } else {
                        buyCarFragment.changNewCarFragment();
                    }
                    if (buyCarFragment.carListFragment != null && buyCarFragment.carListFragment.isAdded()) {
                        buyCarFragment.carListFragment.updateBanner(hasNewCar);
                    }
                }
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + API.get_current_city_activity);
        netDataJson.addParam("city", currentCity);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }



    private void showDownloadSetting() {
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        if (intentAvailable(intent)) {
            startActivity(intent);
        }
    }

    private boolean intentAvailable(Intent intent) {
        PackageManager packageManager = getPackageManager();
        List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }


    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void share() {
        NewCarActivityData.ShareBean shareBean = null;
        if(buyCarFragment != null && buyCarFragment.newCarFragment != null &&buyCarFragment.newCarFragment.newCarActivityData!= null){
            shareBean = buyCarFragment.newCarFragment.newCarActivityData.getShare();
        }
        if(shareBean != null){
            String url = shareBean.getLink();
            String title = shareBean.getTitle();
            String content = shareBean.getDesc();
            UMImage image = new UMImage(MainActivity.this, shareBean.getImage_url());
            new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                    .withTitle(title)
                    .withMedia(image)
                    .withText(content)
                    .withTargetUrl(url)
                    .setCallback(umShareListener)
                    .open();
        }

    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(MainActivity.this, "分享成功!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(MainActivity.this, " 分享失败!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(MainActivity.this, "分享取消!", Toast.LENGTH_SHORT).show();
        }
    };

}
